﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.CoreBusinessLogic.Security;
using SCMS.CoreBusinessLogic.SalaryPayment;
using SCMS.CoreBusinessLogic.OrderRequest;
using SCMS.CoreBusinessLogic.WB;
using SCMS.UI.GeneralHelper;
using SCMS.Model;
using SCMS.UI.Models;
using System.Text;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.NotificationsManager;

namespace SCMS.UI.Controllers
{
    [MyException]
    public class SalaryPamentController : PortalBaseController
    {
        private ISalaryPaymentService SalaryPService;
        private IOrderRequest oRService;
        private IWayBillService WBService;
        private INotificationService notificationService;

        public SalaryPamentController(IPermissionService permissionService, IUserContext userContext, ISalaryPaymentService SalaryPService, IOrderRequest oRService,
            IWayBillService WBService, INotificationService notificationService)
            : base(userContext, permissionService)
        {
            this.SalaryPService = SalaryPService;
            this.oRService = oRService;
            this.WBService = WBService;
            this.notificationService = notificationService;
        }
        //
        // GET: /SalaryPament/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadSalaryPayment()
        {
            Models.SalaryPayment model = new Models.SalaryPayment();
            model.EntitySalaryP = new Model.SalaryRequest();
            model.Currencies = new SelectList(oRService.GetCurrencies(countryProg.Id), "Id", "ShortName");
            model.Months = new SelectList(new[] { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JULY", "AUG", "SEPT", "OCT", "NOV", "DEC" }.ToList());
            model.Offices = new SelectList(WBService.GetSubOffices(countryProg.Id), "Id", "Name");
            model.EntitySalaryP.RefNumber = "--NEW SPM--";
            model.EntitySalaryP.PayrollYear = DateTime.Today.Year;
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveSalaryPayment(Models.SalaryPayment entity)
        {
            entity.EntitySalaryP.Id = Guid.NewGuid();
            entity.EntitySalaryP.CountryProgrammeId = countryProg.Id;
            entity.EntitySalaryP.PreparedBy = currentStaff.Id;
            entity.EntitySalaryP.TotalPayroll = 0;
            entity.EntitySalaryP.IsReviewed = false;
            entity.EntitySalaryP.IsAuthorized = false;
            entity.EntitySalaryP.PreparedOn = DateTime.Now;

            UserSession.CurrentSession.NewSPM = entity.EntitySalaryP;
            return PopulateCreateItem(entity.EntitySalaryP.Id.ToString(), entity.EntitySalaryP.SalaryCurrencyId.ToString());
        }

        private ActionResult PopulateCreateItem(string id, string CurrencyId, string errormessage = "")
        {
            List<ProjectDonor> pdList = oRService.GetProjectNos(countryProg.Id);
            List<BudgetLineView> blList = pdList.Count > 0 ? oRService.GetProjectBugdetLines(pdList[0].Id) : null;
            if (blList == null)
                blList = new List<BudgetLineView>();
            SalaryPaymentItems model = new SalaryPaymentItems()
            {
                EntitySalaryPBL = new SalaryBudgetline(),
                ProjectNos = new SelectList(pdList, "Id", "ProjectNumber"),
                BudgetLines = new SelectList(blList, "Id", "Description"),
                Items = new SelectList(SalaryPService.GetPayrollItems(countryProg.Id), "Id", "Name")
            };
            ViewBag.Action = "Create";
            ViewBag.CurrencyId = CurrencyId;
            ViewBag.SPID = id;
            return View("LoadSalaryPItem", model);
        }

        public ActionResult LoadSalaryPItem(string id)
        {
            return PopulateCreateItem(id.Split('~').First(), id.Split('~').Last());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SaveSPItem(string id, Models.SalaryPaymentItems entity)
        {
            //if (this.IsItemAdded(entity.EntityOrderRequestItem.ItemId, new Guid(id)))
            //{
            entity.EntitySalaryPBL.SalaryId = new Guid(id);
            if (SalaryPService.SaveSalaryReqst(entity.EntitySalaryPBL, UserSession.CurrentSession.NewSPM))
            {
                ViewBag.Response = 1;
                ViewBag.msg = "Process has completed successfully";
                UserSession.CurrentSession.NewSPM = null;
            }
            //}
            //else { ViewBag.Response = 0; ViewBag.msg = "This item is already added"; }
            Models.SalaryPItems modelORDetails;
            List<SalaryBudgetline> TBList = SalaryPService.GetSPBLines(new Guid(id));
            List<SalaryPItems> SPItemsz = new List<SalaryPItems>();
            foreach (SalaryBudgetline bc in TBList)
            {
                modelORDetails = new SalaryPItems();
                modelORDetails.EntitySalaryPBL = bc;
                SPItemsz.Add(modelORDetails);
            }
            ViewBag.CurrencyId = TBList[0].SalaryRequest != null ? TBList[0].SalaryRequest.SalaryCurrencyId.ToString() : Guid.Empty.ToString();
            ViewBag.SPID = id;
            return View("SalarPItemsList", SPItemsz);
        }

        public ActionResult SubmitSPM(Guid id)
        {
            SalaryRequest spm = SalaryPService.GetSalaryRequestById(id);
            spm.PreparedBy = currentStaff.Id;
            spm.PreparedOn = DateTime.Now;
            spm.IsReviewed = false;
            spm.IsAuthorized = false;
            spm.IsSubmitted = true;
            spm.RefNumber = SalaryPService.GenerateUniquNumber(countryProg);
            SalaryPService.SaveApprovedSalaryRequest(spm);
            //Send Notification
            notificationService.SendToAppropriateApprover(NotificationHelper.spmCode, NotificationHelper.reviewCode, spm.Id);
            return ViewSalaryPayment();
        }

        public ActionResult ViewSalaryPayment()
        {
            List<ViewSalaryPayment> modelList = new List<ViewSalaryPayment>();
            List<SalaryRequest> spmlist = SalaryPService.GetSalaryPayments(countryProg.Id);
            foreach (SalaryRequest spm in spmlist)
            {

                var model = new ViewSalaryPayment()
                {
                    EntitySalaryP = spm
                };
                modelList.Add(model);
            }
            return View("ViewSalaryPayment", modelList);
        }

        public ActionResult GetBudgetLines(Guid id)
        {
            StringBuilder blineOption = new StringBuilder();
            blineOption.Append("<select class=\"dpl\" id=\"BudgetLineID\" name=\"EntitySalaryPBL.BudgetLineId\" onchange = \"javascript:checkBalance()\"><option value=\"\">---Please Select---</option>");
            List<Model.BudgetLineView> BLines = oRService.GetProjectBugdetLines(id);
            foreach (BudgetLineView item in BLines)
                blineOption.Append("<option value=\"" + item.Id + "\">" + item.Description + "</option>");
            blineOption.Append("</select>");
            blineOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntitySalaryPBL.BudgetLineId\" data-valmsg-replace=\"true\"></span>");
            ViewBag.Html = blineOption.ToString();
            return View("HTMLResponse");
        }

        public ActionResult ViewSalaryPaymentDetails(Guid id, bool checkPost = false)
        {
            Models.ViewSalaryPayment model = SalaryPaymentExtension.PrepareSP(id);
            //Manage approval link
            string actionType = null;
            if (model.EntitySalaryP.IsReviewed && !model.EntitySalaryP.IsAuthorized)
                actionType = NotificationHelper.authorizationCode;
            else if (model.EntitySalaryP.IsSubmitted && !model.EntitySalaryP.IsReviewed)
                actionType = NotificationHelper.reviewCode;
            if (actionType != null)
                model.CanApprove = notificationService.CanApprove(currentUser, NotificationHelper.spmCode, actionType, model.EntitySalaryP.Id);
            else
                model.CanApprove = false;

            //Manage Post Funds Button
            if (userContext.HasPermission(StandardPermissionProvider.SalaryPaymentPostFunds) && checkPost)
                foreach (var spm in SalaryPService.GetSalaryPaymentsForPosting(countryProg.Id, currentUser))
                {
                    if (spm.Id.Equals(model.EntitySalaryP.Id))
                    {
                        model.CanPostFunds = true;
                        break;
                    }
                }

            return View("ViewSalaryPaymentDetails", model);
        }
    }
}